<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('条款类型')" prop="type">
            <el-select v-model="form.type" :placeholder="$t('条款类型')">
              <el-option
                v-for="dict in typeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('提醒人')" prop="remindUserId">
            <UserSelect v-model="form.remindUserId" :multiple="true" :placeholder="$t('提醒人')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('提醒状态')" prop="status">
            <el-switch
              v-model="form.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-text="$t('开启')"
              :inactive-text="$t('关闭')"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="form.status === 1" :span="12">
          <el-form-item :label="$t('提醒频率')" prop="reminderFrequency">
            <el-radio-group v-model="form.reminderFrequency">
              <el-radio
                v-for="dict in reminderFrequencyOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ $t(dict.dictLabel) }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col v-if="form.status === 1" :span="12">
          <el-form-item :label="form.reminderFrequency === 'TIMER' ? $t('定时提醒时间') : $t('开始提醒时间')" prop="remindTime">
            <el-date-picker
              v-model="form.remindTime"
              clearable
              style="width: 200px"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm"
              :picker-options="pickerOptions"
              :placeholder="form.reminderFrequency === 'TIMER' ? $t('定时提醒时间') : $t('开始提醒时间')"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="form.status === 1 && form.reminderFrequency === 'FREQUENCY' && !isEmpty(form.nextExecution)" :span="12">
          <el-form-item :label="$t('下次执行时间')" prop="remindTime">
            <el-date-picker
              v-model="form.nextExecution"
              clearable
              style="width: 200px"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col v-if="form.reminderFrequency !== 'TIMER' && form.status === 1" :span="24">
          <el-form-item :label="$t('频率提醒表达式')" prop="cron">
            <Cron v-model="form.cron" :cron-value.sync="form.frequencyCronValue" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('关联合同')" prop="associatedContract">
            <el-select v-model="form.associatedContract" :placeholder="$t('关联合同')">
              <el-option
                v-for="(item, index) in associatedContractDict"
                :key="index"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('触发状态')" prop="isTrigger">
            <el-select v-model="form.isTrigger" :placeholder="$t('触发状态')" @change="triggerOnChange">
              <el-option
                v-for="dict in isTriggerOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="isShowTriggerTime" :span="12">
          <el-form-item :label="$t('触发时间')" prop="triggerTime">
            <DatePicker v-model="form.triggerTime" :placeholder="$t('触发时间')" />
          </el-form-item>
        </el-col>
        <el-col v-if="isShowTriggerTime" :span="24">
          <el-form-item :label="$t('应对措施')" prop="responseMethod">
            <el-input v-model="form.responseMethod" type="textarea" :placeholder="$t('应对措施')" show-word-limit maxlength="1000" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('条款内容')" prop="remark">
            <el-input v-model="form.remark" type="textarea" maxlength="2000" :placeholder="$t('条款内容')" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <save-btn :has-permi="hasPermi">
        <template v-slot:after>
          <el-tooltip placement="top">
            <el-button :has-permi="hasPermi" type="success" @click="submitForm('add')">{{ $t('保存并继续新增') }}</el-button>
          </el-tooltip>
        </template>
      </save-btn>
    </div>
  </div>
</template>

<script>
    import { saveDealTermsDebt, getDealTermsDebt } from '@/api/deal/terms/debt/dealTermsDebt'
    import { findByActStatusAndDealId } from '@/api/deal/contract/dealContract'
    import Cron from '@/components/Cron'
    export default {
      components: {
        Cron
      },
      props: {
        hasPermi: {
          type: String,
          default: () => '',
          required: true
        }
      },
        data() {
          var checkTime = (rule, value, callback) => {
            if (!this.isEmpty(value) && this.isEmpty(this.form.id)) {
              console.log(value)
              if (!(value instanceof Date)) {
                value = new Date(value)
              }
              if (value.getTime() > new Date().getTime()) {
                callback()
              } else {
                callback(new Error(this.$t('不能早于当前时间')))
              }
            } else {
              callback()
            }
          }
            return {
                // 条款类型字典
                typeOptions: [], // 是否触发字典
                isTriggerOptions: [], // 表单参数
                isShowTriggerTime: false, // 是否展示触发时间
              // 关联合同下拉
              associatedContractDict: [],
              reminderFrequencyOptions: [],
                form: {},
                // 遮罩层
                loading: false,
                // 表单校验
                rules: {
                  type: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], isTrigger: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], triggerTime: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], remark: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ],
                  remindTime: [{ required: false, validator: checkTime, trigger: 'blur' }]
                },
              pickerOptions: {
                shortcuts: [{
                  text: this.$t('5分钟后'),
                  onClick(picker) {
                    const start = new Date()
                    start.setTime(start.getTime() + 60 * 1000 * 5)
                    picker.$emit('pick', start)
                  }
                }, {
                  text: this.$t('10分钟后'),
                  onClick(picker) {
                    const start = new Date()
                    start.setTime(start.getTime() + 60 * 1000 * 10)
                    picker.$emit('pick', start)
                  }
                }, {
                  text: this.$t('30分钟后'),
                  onClick(picker) {
                    const start = new Date()
                    start.setTime(start.getTime() + 60 * 1000 * 30)
                    picker.$emit('pick', start)
                  }
                }, {
                  text: this.$t('明天'),
                  onClick(picker) {
                    const date = new Date()
                    date.setTime(date.getTime() + 3600 * 1000 * 24)
                    picker.$emit('pick', date)
                  }
                }, {
                  text: this.$t('7天后'),
                  onClick(picker) {
                    const date = new Date()
                    date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
                    picker.$emit('pick', date)
                  }
                }, {
                  text: this.$t('30天后'),
                  onClick(picker) {
                    const date = new Date()
                    date.setTime(date.getTime() + 3600 * 1000 * 24 * 30)
                    picker.$emit('pick', date)
                  }
                }]
              }
          }
        },
        created() {
            this.getDicts('key_terms_tyoe').then(response => {
                this.typeOptions = response.data
            })
            this.getDicts('key_terms_status').then(response => {
                this.isTriggerOptions = response.data
            })
            this.getDicts('reminder_frequency').then(response => {
              this.reminderFrequencyOptions = response.data
            })
            findByActStatusAndDealId(this.$route.query.id).then(response => {
              this.associatedContractDict = response.data
            })
        },
        methods: {
            // 初始化数据
            init(data) {
              this.loading = true
                if (data != null && data.id !== undefined) {
                    getDealTermsDebt(data.id).then(response => {
                        this.form = response.data
                      this.loading = false
                    })
                } else {
                    this.reset()
                  this.loading = false
                }
            },
            // 表单重置
            reset() {
                this.form = {
                id: undefined,
                parentId: undefined,
                dealId: this.$route.query.id,
                type: undefined,
                remindTime: undefined,
                remindUserId: undefined,
                associatedContract: undefined,
                abstracts: undefined,
                isTrigger: undefined,
                triggerTime: undefined,
                responseMethod: undefined,
                remark: undefined,
                createBy: undefined,
                updateBy: undefined,
                createTime: undefined,
                updateTime: undefined,
                delFlag: undefined,
                reminderFrequency: 'TIMER',
                status: 1
                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                this.$parent.$parent.formOpen = false
                // 刷新list页面
                this.$parent.$parent.getList()
            },
            setRest() {
              this.form.responseMethod = undefined
              this.form.remark = undefined
              this.form.summaryContent = undefined
              this.form.createBy = undefined
              this.form.updateBy = undefined
              this.form.createTime = undefined
              this.form.updateTime = undefined
              this.form.delFlag = undefined
              // 关闭form页面遮罩层
              this.loading = false
              // 刷新list页面
              try {
                this.$parent.$parent.getList()
              } catch (e) {
                this.$parent.$parent.$parent.getList()
              }
            },
            /** 提交按钮 */
            submitForm(type) {
                this.$refs['form'].validate(valid => {
                  if (valid) {
                    var that = this
                    if (that.form.parentId !== undefined && that.form.parentId !== null && that.form.parentId !== '') {
                      var contractName = ''
                      this.associatedContractDict.forEach(item => {
                        if (this.form.associatedContract === item.dictValue) {
                          contractName = ' (' + this.$t(item.dictLabel) + ') '
                        }
                      })
                      that.$confirm(that.$t('该条款关联' + contractName + '合同,是否确认修改?'), that.$t('提示'), {
                        confirmButtonText: that.$t('确定'),
                        cancelButtonText: that.$t('取消'),
                        type: 'warning'
                      }).then(() => {
                        that.saveSubmitForm(type)
                      }).catch(() => {
                        console.log('已取消!')
                      })
                    } else {
                      that.saveSubmitForm(type)
                    }
                  } else {
                    this.locationError(document)
                  }
                })
            },
            saveSubmitForm(type) {
              if (this.form.triggerTime === '' || this.form.triggerTime === undefined || this.form.triggerTime === null) {
                this.form.triggerTime = null
              }
              this.loading = true
              // 新增/修改
              saveDealTermsDebt(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess(this.$t('保存成功'))
                  if (type === 'add') {
                    // 保存继续添加
                    this.form.id = undefined
                    this.form.parentId = undefined
                    this.setRest()
                  } else {
                    this.closeForm()
                  }
                } else {
                  this.msgError(response.msg)
                }
                this.loading = false
              })
            },
            triggerOnChange(val) {
              this.form.triggerTime = undefined
              this.form.responseMethod = undefined
              this.isShowTriggerTime = val === 'YCL' || val === 'WCL'
            }

        }

    }
</script>
